package com.xing.poi_dome.utils;

import com.alibaba.fastjson.*;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2024/7/8 14:19
 */
public class PoiUtils {
    public static void template(String filePath, String params, HttpServletResponse response) throws IOException {
        String realFileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".docx";
        realFileName = URLEncoder.encode(realFileName, "UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=" + realFileName);
        response.setCharacterEncoding("UTF-8");
        XWPFTemplate compile = XWPFTemplate.compile(filePath);
        compile.render(params);
        ServletOutputStream os = response.getOutputStream();
        compile.write(os);
    }


    public static Map<String, Object> getMap(String params) {
        Map<String, Object> map = new HashMap<String, Object>();

        JSONObject json = JSONObject.parseObject(params);
        JSONArray list01 = (JSONArray) json.get("list01");
        JSONArray list02 = (JSONArray) json.get("list01");
        JSONArray list03 = (JSONArray) json.get("list01");
        JSONArray table = (JSONArray) json.get("table");
        List<String> jsonArrayToStringList01 = JSONObject.parseArray(list01.toJSONString(), String.class);
        List<String> jsonArrayToStringList02 = JSONObject.parseArray(list02.toJSONString(), String.class);
        List<String> jsonArrayToStringList03 = JSONObject.parseArray(list03.toJSONString(), String.class);
        List<String> jsonArrayToStringList = JSONObject.parseArray(table.toJSONString(), String.class);
        for (String str : jsonArrayToStringList) {
            Map<String, String> jsonMap = JSON.parseObject(str, new TypeReference<HashMap<String, String>>() {
            });
            System.out.println(jsonMap.toString());
        }
        map.put("startTime", json.get("startTime").toString());
        map.put("endTime", json.get("endTime").toString());
        map.put("list01", jsonArrayToStringList01);
        map.put("list02", jsonArrayToStringList02);
        map.put("list03", jsonArrayToStringList03);
        RowRenderData renderData = Rows.create((CellRenderData) jsonArrayToStringList);
        map.put("table", Tables.create(renderData));
        return map;
    }

}
